package com.example.first.thread;

import com.example.first.common.Constant;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @Author LSQ
 * @Description reentrantLock和countDownLatch在定义时都要放在runnable的外面，如果放在里面就不生效！ 我今天也是奇思妙想！
 * @date 2021/11/14 21:47
 * @Version 1.0
 */

public class LearnReentrantLock5 {
    public static int count = 0;

    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(Constant.CORE_POOL_SIZE, Constant.MAX_POOL_SIZE,
                0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(Constant.QUEUE_CAPACITY));

        List<People> peopleList = new LinkedList<>();

        for (int i = 0; i < 20; i++) {
            int index = i + 1;
            String name = "lsq" + index;
            People people = new People(i, name, i + 20, "golf", "$20000");
            peopleList.add(people);
        }

        final CountDownLatch countDownLatch = new CountDownLatch(peopleList.size());
        ReentrantLock reentrantLock = new ReentrantLock(true);

        peopleList.forEach(people -> {

            Worker2 worker = new Worker2(people, countDownLatch, reentrantLock);

            executorService.submit(worker);

        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executorService.shutdown();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (executorService.isTerminated()) {
            System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + " thread pool is terminated!");
        }


    }
}
